<template>
	<view class="wrap">
		<view class="search-bar">
			<view class="search-bar-inp">
				<input v-model="keywords" placeholder="搜索人名/组名" placeholder-style="color:#ccc" type="text" value="" />
				<view class="btn" @click="searchFuc"><uni-icons size="22" color="#0091ff" type="search"></uni-icons></view>
				
				<!-- <uni-search-bar :isShow="true" :radius="0" :value="keywords" clearButton="always" placeholder="搜索人名/组名" @blurs="searchFuc" class="searching"></uni-search-bar> -->
			</view>
			<!-- <view class="search-bar-rig" @click="tabAdmin">
				<text></text>
				<text :style="{color:showTab?'#0091ff':''}">{{showTab?'完成':'管理'}}</text>
			</view> -->
		</view>
		<!-- <view class="titTexts" v-if="showTab">
			<view class="">快捷设置:</view>
			<view class="def" @click="defaultSet">默认设置</view>
			<view class="def" @click="defaultStep">上次设置</view>
		</view> -->
		<!-- <view class="titText" v-if="!showTab">
			点击【管理】入口，可自定义管理需要统计的人员信息
		</view> -->
		
		<!-- <treeNodeSelect v-if="showTab" ref="treePicker" :multiple='true' @select-change="selectChange" title=""
			:localdata="treeData" :selectedData="selectedData" valueKey="id" textKey="title" childrenKey="children" /> -->
		
		<memberTree v-if="!showTab" :isState="2" :selectIds="selectIds" :selectGroup="selectGroup" :tree="treeData" @node-click="nodeClick"></memberTree>
		<view class="bottom-block">
			
		</view>
	</view>
</template>

<script>
import memberTree from '@/components/member-tree/member-tree.vue';
import { getMembers } from '@/apis/building.js';
import { hanleToken } from '@/utils/utils.js';
import { repairPlanDetail, approvePlan,reApproveUsers } from '@/apis/approve.js';
import unisearchbar from '@/components/uni-search-bar/uni-search-bar.vue';
import {getSignDeptTree} from '@/apis/statisticalTotal.js';
import {delRepeat} from '@/utils/tools.js';
export default {
	components: { 
		memberTree,
		unisearchbar,
	},
	name:'siginUserList',
	data() {
		return {
			keywords: '',
			tree: [],
			treeData: [],// 树形数据
			checkArr: [], // 勾选的数据
			expandedIds: [], // 用于点击打开子级
			form: {},
			showTab:false,
			allUserArr:[],//
			selectedData:[],// 默认选择数据
			selectIds:'',// ids
			selectGroup:'',
			
		};
	},
	computed: {
		isState() {
			return this.checkArr.length || false;
		}
	},
	onLoad(os) {
		uni.showLoading({
			title: '加载中',
			mask: true
		});
		
		getSignDeptTree().then(data => {
			if (data.code === 200) {
				uni.hideLoading();
				let arrTree =  data.data;
				this.tree = arrTree;
				// this.foopDeep(arrTree,[],this)
				this.treeData = JSON.parse(JSON.stringify(arrTree));
				let allSelectUser = this.getMemberIds(arrTree,[]);
				let allSelectGroup = this.getGroups([arrTree[0]],arrTree[0].id);// 第一级组列表 
				let allArrs = [];
				for (let i = 0; i < allSelectGroup.length; i++) {
					allArrs.push(allSelectGroup[i].id);
				} 
				this.selectIds = allSelectUser.join(',');
				this.selectGroup = allArrs.join(',');
				
				uni.getStorage({
					key: 'statisticalSign',
					success: res => {
						if (res) {
							this.selectIds = res.data.id;
							let selectGroup = res.data.id; 
							let selectGroupArr = [];
							let arr = [];
							let selectAllArr = [];
							if (res.data.groupList) {
								for (let i = 0; i < res.data.groupList.length; i++) {
									  arr.push(res.data.groupList[i].id);
									  selectGroupArr.push(res.data.groupList[i].id);
								}
								selectGroup = arr.join(',');
							}
							let newArr = res.data.id.split(',');
							if (res.data.groupList) {
								newArr = newArr.concat(arr);
							}
							this.selectGroup = selectGroup; 
							this.selectedData = newArr;// 编辑时默认显示已勾选状态
							console.log('缓存',res,this.selectGroup,this.selectIds);
						}
					}
				});
				
				console.log('Treeeee',data,allSelectUser,allSelectGroup);
			}
		});
	},
	
	methods: {
		// 搜索
		searchFuc(val) {
			// console.log('hahhahaha', val);
			// this.keywords = val;
			if (this.keywords === '') {
				this.treeData = JSON.parse(JSON.stringify(this.tree));
			} else {
				// this.expandedIds = [];
				this.treeData = this.filterTree(JSON.parse(JSON.stringify(this.tree)),this.keywords);
			}
		},
		selectChange(val) {
			console.log('选择了。。。。',val);
		},
		// 点击每一项
		nodeClick(res) {
			console.log('nodeClick', res);
		
			if (res.type == 2 || res.showTotal) {
				// type2 ==>人员  showTotal==>组
				
				this.toDetail(res);
			}
		},
		// 前往统计详情
		toDetail(res) {
			let obj = {}; 
			let mbs = [];
			let groups = [];
			if (res.showTotal) {
				mbs = this.getMemberIds(res.parent.children,[]); 
				groups = this.getGroups(res.parent.children,res.id);// 第一级组列表 
				 
				mbs = delRepeat(mbs); 
				for (let i = 0; i < groups.length; i++) {
					groups[i].children = delRepeat(groups[i].children,'id');
				} 
				// 组维度 查找全部人员id
				obj = {
					id:mbs.join(','),
					groupList:groups,
					title:res.parent.title,
					groupId:res.parent.id,
					type:res.type
				};
			} else {
				// 人员维度
				obj = {
					id:res.id,
					title:res.title,
					groupId:res.parent.id,
					type:res.type
				};
			}
			// let isStates = false
			// if(this.selectedData.length > 0){
			// 	this.selectedData = delRepeat(this.selectedData) 
			// 	isStates = !this.selectedData.some((item)=>item == res.id)
			// }
			// if(isStates){
			// 	return
			// }
			
			uni.setStorage({
			    key: 'statisticalSign',
			    data: obj,
			    success: () => {
					// uni.$emit('setDataSign',{})
					uni.navigateBack({
						delta:1
					}); 
			    }
			});
		  
			console.log('前往统计详情', obj);
		},
		
		// 管理
		tabAdmin() {
			this.showTab = !this.showTab;
			if (!this.showTab) {// 完成点击
				let obj = this.$refs.treePicker._confirm();
				let userArr = [];
				let groupArr = [];
				let groupAllUserId = [];
				let strSelectIds = '',strSelectGroup = '';
				if (obj.selectedList && obj.selectedList.length > 0) {
					obj.selectedList.map(item=>{
						if (item.type === 1) {// 获取组的id
							groupArr.push(item.id);
						}
						if (item.type === 2) {// 获取人的id
							userArr.push(item.id);
						}
					});
					userArr = delRepeat(userArr); 
					
					if (groupArr.length > 0) {
						groupAllUserId = this.getUsersList(this.treeData,groupArr);// 获取组下面的所有人
						strSelectGroup = groupAllUserId.map((item)=>item.id).join(',');
						strSelectGroup = strSelectGroup + ',' + groupArr.join(',');
					}
					if (userArr.length > 0) {
						strSelectIds = userArr.join(',');
						if (groupAllUserId.length > 0) {
							strSelectIds = userArr.join(',') + ',' + groupAllUserId.map((item)=>item.id).join(',');
						}
					}
					
				 this.selectGroup = strSelectGroup;
				 this.selectIds = strSelectIds;
				 
					// this.selectedData = userArr.concat(groupArr)
				}
			} else {
				let newArrG = [],newArrU = []; 
				if (this.selectGroup.length > 0) {
					newArrG = this.selectGroup.split(',');
				}
				if (this.selectIds.length > 0) {
					newArrU = this.selectIds.split(',');
					newArrU = delRepeat(newArrU); 
				}
				this.selectedData = newArrG.concat(newArrU);
			}
		},
		// 获取第一级组列表
		getGroups(list,groupId) {
			let arr = []; 
			let other = {
				id:groupId,
				type:1,
				name:'其他',
				isMore:true,
				children:[]
			};
			for (let i = 0; i < list.length; i++) { 
				if (list[i].type == 1) {
					arr.push({
						id:list[i].id,
						name:list[i].title,
						type:1,
						children:this.getMemberList(list[i].children || [],[])
					});
				} else {
					other.children.push({
						id:list[i].id,
						name:list[i].title,
						type:2 
					});
				}
			}
			if (other.children.length) {
				arr.push(other);
			}
			return arr;
		},
		
		// 获取全部人员
		getMemberList(nodes, arr) {
			if (nodes && nodes.length) {
				for (let i = 0; i < nodes.length; ) {
					if (nodes[i].type == 2) {
						arr.push({
							id:nodes[i].id,
							name:nodes[i].title,
							type:2
						});
					} else { 
						if (nodes[i].children && nodes[i].children.length > 0) {
							arr = arr.concat(this.getMemberList(nodes[i].children, []));
						}
					}
					i++;
				}
			} 
			
			return arr;
		},
		// 根据组id获取组人员
		getUsersList(deArr,parentArr) {
			let arr = [];
			if (deArr && deArr.length > 0 ) {
				for (let i = 0; i < deArr.length; i++) {
					for (let j = 0; j < parentArr.length; j++) {
						if (deArr[i].type === 1 && deArr[i].id == parentArr[j]) {
							arr.push(...deArr[i].children);
						}
					}
					if (deArr[i].children && deArr[i].children.length > 0) {
						arr = arr.concat(this.getUsersList(deArr[i].children,parentArr));
					}
				}
			} 
			return arr;
		},
	
		// 递归获取组下所有用户id
		getMemberIds(nodes, arr) {
			if (nodes && nodes.length) {
				for (let i = 0; i < nodes.length; ) {
					if (nodes[i].type == 2) {
						arr.push(nodes[i].id);
					} else { 
						if (nodes[i].children && nodes[i].children.length > 0) {
							arr = arr.concat(this.getMemberIds(nodes[i].children, []));
						}
					}
					i++;
				}
			} 
			
			return arr;
		},
		//
		foopDeep(data,arr,that,numArr) {
			if (data && data.length > 0) {
				for (let i = 0; i < data.length; i++) {
					if (data[i].type === 2) {
						console.log('信息',data[i]);
						data[i].allUser = '全部组员';
					}
					if (data[i].children && data[i].children.length > 0) {
						that.foopDeep(data[i].children,arr,that,numArr);
					}
				}
			}
		},
		// 默认设置
		defaultSet() {
			this.selectedData = ['1496414797434351617'];
			console.log('默认设置',this.selectedData);
		},
		// 上一次设置
		defaultStep() {
			
		},
		// 分配任务
		imTasksClick() {
			if (this.checkArr.length > 0) {
				if (this.form.id) {
					uni.showLoading({
						title: '提交中',
						mask: true
					});
					console.log('选中的人',this.checkArr);
					let assignUsers = [];
					for (let i = 0; i < this.checkArr.length; i++) {
						if (assignUsers.indexOf(this.checkArr[i].id) == -1) {
							assignUsers.push(this.checkArr[i].id);
						}
					}
					let data = {
						...this.form
						
					};
					if (this.form.planId) {
						data.userIds = assignUsers;
					} else {
						data.assignUsers = assignUsers;
					}
					(this.form.planId ? reApproveUsers : approvePlan)(data).then(res => {
						uni.hideLoading();
						uni.showModal({
							title: '提示',
							content: '分配成功',
							showCancel: false,
							success: () => {
								uni.navigateBack({
									delta: 1
								});
							}
						});
					});
				} else {
					hanleToken('set', 'planUserArr', this.checkArr);
					uni.navigateBack({
						delta: 1
					});
				}
			}
		},

		// 关键词过滤
		filterTree(nodes, query) {
			// 条件就是节点的title过滤关键字
			let predicate = function(node) {
				return node.title.includes(query);
			};

			// 结束递归的条件
			if (!(nodes && nodes.length)) {
				return [];
			}
			let newChildren = [];
			for (let node of nodes) {
				if (node.children && node.children.length) {
					node.show = true;
				}

				// 一、带父节点     以下两个条件任何一个成立，当前节点都应该加入到新子节点集中
				// 1. 子孙节点中存在符合条件的，即 subs 数组中有值
				// 2. 自己本身符合条件
				let subs = this.filterTree(node.children, query);
				if (predicate(node)) {
					newChildren.push(node);
				} else if (subs && subs.length) {
					node.children = subs;
					newChildren.push(node);
					this.expandedIds.push(node.id);
				}

				// 二、不带父节点     以下只需要考虑自身的节点满足条件即可,不用带上父节点
				// if (predicate(node)) {
				// 	newChildren.push(node);
				// 	node.children = this.filterTree(node.children, query);
				// } else {
				// 	newChildren.push(...this.filterTree(node.children, query));
				// }
			}
			return newChildren.length ? newChildren : [];
		}
	}
};
</script>

<style lang="scss" scoped>
	page {
		background-color: #f6f6f6;
		color: #333;
		width: 100%;
	}
	.wrap {
		background-color: #f6f6f6;
		width: 100%;
		min-height: 100vh;
		
	}
	.bottom-block{
		width: 100%;
		height:240rpx;
	}
	
	.search-bar {
		background-color: #fff;
		width: 100%;
		margin-bottom: 16rpx;
		display: flex;
		.search-bar-inp {
			width: 710rpx;
			margin: 24rpx auto;
			background-color: #f6f6f6;
			border-radius: 8rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			input {
				font-size: 26rpx;
				flex: 1;
				padding: 12rpx 28rpx;
			}
			.btn {
				width: 90rpx;
				text-align: center;
				height: auto;
				display: flex;
				justify-content: center;
				align-items: center;
			}
		}
		.search-bar-rig{
			flex: 0 0 124rpx;
			width: 124rpx;
			height: 102rpx;
			line-height: 102rpx;
			text-align: center;
			position: relative;
			text:nth-of-type(1){
				display: inline-block;
				position: absolute;
				top: 38rpx;
				left: 15rpx;
				height: 36rpx;
				border-left:2rpx #ccc solid;
			}
			text:nth-of-type(2){
				font-size: 26rpx;
				font-weight: 400;
				color: #333333;
				margin-left: 12rpx;
			}
		}
		.searching {
			width: 100%;
			padding: 0;
		}
	}
	.titText{
		height:66rpx;
		line-height: 66rpx;
		text-align: center;
		font-size: 24rpx;
		font-weight: 400;
		color: #999999;
	}
	.titTexts{
		height:66rpx;
		line-height: 66rpx;
		border-top: 2rpx #e9e9e9 solid;
		border-bottom: 2rpx #e9e9e9 solid;
		display: flex;
		align-items: center;
		background-color: #fff;
		view:nth-of-type(1){
			margin-left: 20rpx;
			font-size: 24rpx;
			color: #999999;
		}
		.def{
			width: 136rpx;
			height: 36rpx;
			text-align: center;
			line-height: 36rpx;
			border: 2rpx solid #cccccc;
			border-radius: 20rpx;
			font-size: 24rpx;
			color: #666666;
			margin: 0 10rpx;
		}
		
	}
</style>
